<template>
  <div>
    <div class="table-header">
      <el-row>
        <el-col :span="9"> 车辆信息 </el-col>
        <el-col :span="4"> 单价 </el-col>
        <el-col :span="5"> 数量 </el-col>
        <el-col :span="4"> 金额 </el-col>
        <el-col :span="2"> 交易操作 </el-col>
      </el-row>
    </div>

    <div class="table-body">
      <div
        class="table-body_have"
        v-if="tableData.length > 0"
        v-loading="loading"
        v-for="(item, index) in tableData"
        :key="index"
      >
        <div class="company-name">
          <div>{{ item.sellerName }}</div>
        </div>
        <!-- 0-待审批，1-已驳回， 2-已上架，3-下架 -->
        <div v-for="(d, j) in item.list" :key="j">
          <el-divider></el-divider>
          <div class="pd-lg" :class="d.status === 3 ? 'goods-disabled' : ''">
            <el-row>
              <el-col :span="1" class="flex-y-center">
                <el-checkbox
                  :value="true"
                  v-model="d.chenked"
                  @change="onCheckBoxChecked(index, j)"
                >
                </el-checkbox>
              </el-col>
              <el-col :span="8">
                <div class="flex">
                  <div class="goods-img">
                    <img :src="d.productDetail.prodcutPicList.thumbnailUrl" />
                  </div>
                  <div class="ml-md mr-md goods-info flex-1">
                    <div class="goods-name">
                      {{ d.productTitle }}
                    </div>
                    <div class="flex-y-center goods-port">
                      <div>
                        <span> 启运港：</span>
                        <span>{{ d.country }} &nbsp;</span>
                        <span>{{ d.city }} &nbsp;</span>
                        <span>{{ d.harbor }}</span>
                      </div>
                      <div class="goods-removed" v-if="d.status === 3">
                        已下架
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="4" class="flex-yx-center">
                <span>{{ d.productCurrency }}</span>
                <span class="ml-sm">{{
                  filters.thousands(d.productPrice)
                }}</span>
              </el-col>
              <el-col :span="5" class="flex-yx-center">
                <div class="flex-1">
                  <el-input-number
                    :min="1"
                    class="wh"
                    :max="d.stockAmount * 1"
                    v-model="d.amount"
                    @change="onGoodsNumber(d)"
                  ></el-input-number>
                </div>
                <div class="ml-lg f-s-14">库存 {{ d.stockAmount }} 台</div>
              </el-col>
              <el-col :span="4" class="flex-yx-center">
                <span>{{ d.productCurrency }}</span>
                <span class="ml-sm">{{ itemSumMoney(d) }}</span>
                <!--  filters.thousands(d.sumProductPrice) -->
              </el-col>
              <el-col :span="2" class="flex-yx-center goods-del">
                <el-link type="danger" :underline="false" @click="handleDel(d)"
                  >删除</el-link
                >
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
      <!-- 无数据的时候 -->
      <div class="table-body_empty flex-center" v-else v-loading="loading">
        <el-empty :image="empty" />
      </div>
    </div>
    <div class="table-footer mt-lg">
      <div class="table-footer_content flex-1">
        <div class="f-s-14">
          <span>共</span>
          <span class="c-EE5B5B mr-sm ml-sm">{{ sumTotal.sumNumber }}</span>
          <span>台车辆，已选择</span>
          <span class="c-EE5B5B mr-sm ml-sm">{{ sumTotal.checkedNumber }}</span>
          <span>台</span>
        </div>
        <div>
          <span class="f-s-14">应付金额：</span>
          <span class="c-EE5B5B f-s-16 mr-sm">{{ sumTotal.currency }}</span>
          <span class="c-EE5B5B f-s-24 f-w-bold">{{ sumTotal.price }}</span>
        </div>
      </div>
      <div
        class="table-footer_button flex-center pointer"
        @click="handleSubmit"
      >
        <span>马上结算</span>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, getCurrentInstance, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useBasicsTable } from "@/hooks/useTable.js";
import { multiplication, addition } from "@/utils/compute.js";
import { deepClone } from "@/utils/index.js";
const router = useRouter();
const empty = new URL(`@/assets/img/table-kong.png`, import.meta.url).href;
const tableData = ref([]);
const loading = ref(false);
const { proxy } = getCurrentInstance();
const itemSumMoney = computed(() => {
  return (item) => {
    const n = multiplication(item.productPrice, item.amount);
    return proxy.filters.thousands(n);
  };
});
const sumTotal = computed(() => {
  const list = [];
  tableData.value.forEach((x) => {
    x.list.forEach((r) => {
      list.push(r);
    });
  });
  const checkedList = list.filter((x) => x.chenked);
  const items = {
    currency: "-",
    price: 0,
    sumNumber: list.length,
    checkedNumber: checkedList.length,
  };

  if (checkedList && checkedList.length > 0) {
    items.currency = checkedList[0].productCurrency;
    const n = checkedList.reduce((x, y) => {
      return addition(x, multiplication(y.productPrice, y.amount));
    }, 0);
    items.price = proxy.filters.thousands(n);
  }
  return items;
});
const onCheckBoxChecked = (i, j) => {
  const item = deepClone(tableData.value[i].list[j]);
  tableData.value = tableData.value.map((x) => {
    x.list.map((r) => {
      if (item.productId === r.productId) {
        r.chenked = true;
      } else {
        r.chenked = false;
      }
      return r;
    });
    return x;
  });
  // // 查询有没一重复值
  // const d = multiples.value.find((x) => {
  //   return ( x.productCurrency !== item.productCurrency || x.sellerId !== item.sellerId );
  // });
  // // 查询有没一重复商品
  // const index = multiples.value.findIndex((x) => {
  //   return x.productId === item.productId;
  // });
  // if (!d && index >= -1 && item.chenked) {
  //   // 没一重复值 并且数组没有相同商品Id 并且选中状态 追加
  //   multiples.value.push(item);
  // } else if (!d && item.chenked) {
  //   // 没一重复值 并且选中状态 直接替换
  //   multiples.value[index] = item;
  // } else if (!d && !item.chenked) {
  //   // 没一重复值 并且未状态 直接删除
  //   multiples.value.splice(index,1)
  // }else {
  //   // 不可以勾选
  //   tableData.value[i].list[j].chenked = false
  // }
};
const onGoodsNumber = async (item) => {
  const url = "/buyerShoppingCart/insert";
  const data = {
    amount: item.amount,
    productId: item.productId,
  };
  await proxy.$post({ url, data });
};
const handleSubmit = () => {
  let item = {};
  tableData.value.forEach((x) => {
    x.list.forEach((r) => {
      if (r.chenked) item = r;
    });
  });
  if (!item.productId) {
    ElMessage.warning("请选择结算车辆");
    return;
  }
  router.push({
    path: "/Order/ConfirmOrder",
    query: {
      productId: item.productId,
      amount: item.amount,
      scene: 1,
    },
  });
};
const handleDel = (item) => {
  ElMessageBox.confirm("确认从购物车中删除所选商品吗？", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      loading.value = true;
      const url = "/buyerShoppingCart/delete";
      const params = {
        id: item.id,
      };
      await proxy.$get({ url, params });
      getList();
    } catch (error) {
      loading.value = false;
    }
  });
};
onMounted(() => {
  getList();
});
const getList = () => {
  loading.value = true;
  const url = "/buyerShoppingCart/list";
  proxy.$get({ url }).then((res) => {
    const list = [];
    for (let i = 0; i < res.length; i++) {
      const index = list.findIndex((x) => x.sellerId === res[i].sellerId);
      res[i].chenked = false;
      if (index === -1) {
        const item = {
          sellerId: res[i].sellerId,
          sellerName: res[i].sellerName,
          list: [res[i]],
        };
        list.push(item);
      } else {
        list[index].list.push(res[i]);
      }
    }
    loading.value = false;
    tableData.value = list;
  });
};
</script>
<style lang="less" scoped>
:deep(.el-divider--horizontal) {
  margin: 12px 0 0 0 !important;
}
:deep(.el-input-number__decrease) {
  background: transparent !important;
}
:deep(.el-input-number__increase) {
  background: transparent !important;
}

.table-header {
  background: #fff;
  padding: 10px;
  font-size: 14px;
  color: #26282a;
  text-align: center;
  margin-bottom: 15px;
}
.table-body {
  min-height: 450px;
  .table-body_empty {
    width: 100%;
    background: #ffffff;
    margin: auto;
    height: 450px;
  }
  .table-body_have {
    background: #fff;
    margin-bottom: 15px;
    font-size: 14px;
    color: #26282a;
    height: 100%;
    .company-name {
      font-size: 14px;
      padding-top: 12px;
      padding-left: 50px;
      font-weight: 400;
      color: #202020;
    }
    .goods-disabled {
      opacity: 0.5;
      pointer-events: none;
      .goods-del {
        z-index: 9999;
        pointer-events: auto;
      }
    }
    .goods-img {
      width: 96px;
      height: 72px;
      border: 1px dashed rgba(0, 0, 0, 0.17);
    }
    .goods-info {
      display: flex;
      flex-direction: column;
      .goods-name {
        font-size: 14px;
        color: #202020;
        margin: auto 0;
      }
      .goods-port {
        font-size: 14px;
        color: #7c7c7c;
        font-weight: 400;
        margin: auto 0;
      }
      .goods-removed {
        background: #f0f8fd;
        margin-left: 12px;
        padding: 3px 5px;
        color: #448be9;
        border-radius: 5px;
      }
    }
  }
}

.table-footer {
  background: #ffffff;
  display: flex;
  align-items: center;
  height: 54px;
  .table-footer_content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 20px;
  }
  .table-footer_button {
    width: 148px;
    height: 54px;
    background: linear-gradient(65deg, #6cbbfb 0%, #3a85f5 100%);
    font-size: 16px;
    color: #ffffff;
  }
}
</style>